from flask import request


def build_tree_nodes(nodes):
    node_dict = {node["id"]: node for node in nodes}
    tree = []

    for node in nodes:
        parent_id = node.get("parent_id", None)
        if parent_id is None:
            tree.append(node)
        else:
            parent_node = node_dict.get(parent_id)
            if parent_node:
                parent_node.setdefault("children", []).append(node)

    return tree


def find_method(methods):
    _methods = {"DELETE", "POST", "GET", "PUT", "PATCH"}
    for method in methods:
        if method in _methods:
            return method


def find_api_name(endpoint):
    return endpoint.split(".")[-1]


def parse_ip():
    ip = request.headers.get("X-Real-IP")
    if not ip:
        ip = request.remote_addr
    return ip
